package com.zh.kmmsample.android

import android.app.Activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.zh.kmmsample.android.item.WenDaItem
import com.zh.kmmsample.http.Api
import com.zh.kmmsample.model.WenDaModel
import com.zh.kmmsample.util.HttpUtil
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent() {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    ContentView(this)
                }
            }
        }
    }
}

@Composable
fun ContentView(context: Activity) {
    Column {
        val scope = rememberCoroutineScope()
        var wenDaModel by remember {
            mutableStateOf(WenDaModel())
        }

        //按钮
        Button(
            modifier = Modifier
                .padding(10.dp)
                .fillMaxWidth(),
            onClick = {
                scope.launch {
                    wenDaModel = HttpUtil.get(
                        url = Api.wenDaApi
                    )
                }
            }) {
            Text(text = "请求数据")
        }

        //列表
        LazyColumn {
            repeat(
                wenDaModel.data?.datas?.size ?: 0
            ) {
                item {
                    val data = wenDaModel.data?.datas?.get(it)
                    WenDaItem(data = data) {
                        WebViewActivity.start(context, data?.link)
                    }
                }
            }
        }
    }
}